/* 
 *  javascribd - Java client library for the Scribd API. 
 *  Copyright (C) 2009 by Marcel Eyke, http://code.google.com/p/javascribd/ 
 *  Use is subject to license terms of LGPL. See license.txt. 
 */
package com.google.code.javascribd.connection.jaxbadapter;

import java.text.NumberFormat;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import com.google.code.javascribd.type.Date;

public class DateAdapter extends XmlAdapter<String, Date> {
	private final NumberFormat formater;
	{
		formater = NumberFormat.getInstance();
		formater.setMinimumIntegerDigits(2);
	}

	@Override
	public String marshal(Date date) throws Exception {
		if (date == null) {
			return null;
		}
		return date.getYear() + "-" + formater.format(date.getMonth()) + "-" + formater.format(date.getDay());
	}

	@Override
	public Date unmarshal(String dateString) throws Exception {
		if (dateString == null) {
			return null;
		}
		return toDate(dateString.trim());
	}

	private Date toDate(String s) {
		int year;
		int month;
		int day;
		int firstDash;
		int secondDash;

		assert s != null;

		firstDash = s.indexOf('-');
		secondDash = s.indexOf('-', firstDash + 1);
		if ((firstDash > 0) & (secondDash > 0) & (secondDash < s.length() - 1)) {
			year = Integer.parseInt(s.substring(0, firstDash));
			month = Integer.parseInt(s.substring(firstDash + 1, secondDash));
			day = Integer.parseInt(s.substring(secondDash + 1));
		} else {
			throw new java.lang.IllegalArgumentException();
		}

		return new Date(year, month, day);
	}
}
